package com.hiof.servercommunication.background.job;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.hiof.Configuration;
import com.hiof.servercommunication.background.job.listener.IListener;
import com.hiof.servercommunication.exception.NetworkException;
import com.hiof.servercommunication.exception.ServerException;
import com.hiof.servercommunication.receive.beans.Packet;
import com.hiof.utility.Utility;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 4/1/12
 * Time: 11:38 AM
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractJob {
    public AbstractJob(Packet sendData) {
        this.sendData = sendData;
    }

    public AbstractJob() {
    }

    public Packet getSendData() {
        return sendData;
    }

    public List<IListener> listeners = new ArrayList<IListener>();
    public Packet sendData;

    protected abstract Packet connect2Server() throws ServerException, NetworkException;

    public void addListener(IListener listener) {
        listeners.add(listener);
    }

    public void removeListener(IListener listener) {
        if (null != listeners && listeners.contains(listener)) {
            listeners.remove(listener);
        }
    }

    public void executeJob() {
        try {
            Packet packet = connect2Server();
            if (packet != null) {
                Message msg = new Message();
                msg.obj = packet;
                finishJobHandler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("error: ", e.getMessage());
            msg.setData(bundle);
            exceptionHandler.sendMessage(msg);
        }
    }

    public void handlerJobDone(Packet packet) {
        for (IListener listener : listeners) {
            listener.onListen(packet);
        }
    }

    Handler exceptionHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(Configuration.getInstance().getCurrentContext(), String.valueOf(msg.getData()), Toast.LENGTH_SHORT);
            Utility.error(AbstractJob.class.toString(), "Exception while executing the job " + String.valueOf(msg.getData()));
        }
    };

    Handler finishJobHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handlerJobDone((Packet) msg.obj);
        }
    };
}
